package com.duan.order.controller;

import com.duan.entity.Result;
import com.duan.order.pojo.Order;
import com.duan.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/notify")
public class NotifyController {
    @Autowired
    private OrderService orderService;
    /**
     * 支付宝回调
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/aliNotify")  // 注意这里必须是POST接口
    public Result payNotify(HttpServletRequest request) throws Exception {
        System.out.println("=========支付宝异步回调========");
        Order order = new Order();
        // 支付成功，修改订单
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            order.setId(Long.valueOf(params.get("out_trade_no")));
            order.setStatus(2);
            order.setTradeNo(params.get("trade_no"));
            orderService.update(order);
            return new Result("success");
        }else {
            // 支付失败，关闭订单
            order.setStatus(7);
            orderService.update(order);
        }
        return Result.fail("支付失败，关闭订单");
    }
}

